package com.csu.common.handler;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

/**
 * 
 * @项目名称：express
 * @类名称：CORSFilter
 * @类描述：
 * @创建人：Tangc
 * @创建时间：2017年10月17日 下午7:00:46
 * @company:
 */
public class CORSFilter implements Filter
{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException
    {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        //HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");

        //String origin = httpRequest.getHeader("origin");
        //httpResponse.setHeader("Access-Control-Allow-Origin", isEmpty(origin) ? "*" : origin);
        httpResponse.setHeader("Access-Control-Expose-Headers ", "token,x-requested-with,content-type,No-Cache"); // 允许跨域请求获取header

        httpResponse.setHeader("Access-Control-Request-Method ", "GET,POST,PUT,DELETE,OPTIONS");
        httpResponse.setHeader("Access-Control-Request-Headers ", "token,x-requested-with,content-type,No-Cache");
        httpResponse.setHeader("Access-Control-Allow-Methods ", "GET,POST,PUT,DELETE,OPTIONS");
        httpResponse.setHeader("Access-Control-Allow-Headers ", "token,x-requested-with,,content-type,No-Cache");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * @description
     * @author TangC
     * @date 2017年12月8日 下午10:09:11
     * @param origin
     * @return
     */
    public boolean isEmpty(String origin)
    {
        return (StringUtils.isEmpty(origin)) || ("(null)".equals(origin)) || ("null".equals(origin));
    }

    @Override
    public void destroy()
    {

    }
}